﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace LJSheng.Web.live
{
    /// <summary>
    /// ksapi 的摘要说明
    /// </summary>
    public class ksapi : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string zbj = string.IsNullOrEmpty(context.Request.Form["zbj"]) ? context.Request.QueryString["zbj"] : context.Request.Form["zbj"];
            string sn = string.IsNullOrEmpty(context.Request.Form["sn"]) ? context.Request.QueryString["sn"] : context.Request.Form["sn"];
            string path = System.Web.HttpContext.Current.Server.MapPath("/live/");
            string filename = path + sn + ".html";
            if (File.Exists(filename))
            {
                context.Response.Write(GetKS(zbj));
            }
            else
            {
                context.Response.Write(GetKS("haishi_1229"));
            }
            context.Response.End();
        }

        public static string GetKS(string zbj)
        {
            string WebSockToken = zbj;
            string liveStreamId = "";
            try
            {
                var LiveDetail = new
                {
                    operationName = "LiveDetail",
                    variables = new { principalId = zbj },
                    query = "query LiveDetail($principalId: String) {\n  webLiveDetail(principalId: $principalId) {\n    liveStream\n    feedInfo {\n      pullCycleMillis\n      __typename\n    }\n    watchingInfo {\n      likeCount\n      watchingCount\n      __typename\n    }\n    noticeList {\n      feed\n      options\n      __typename\n    }\n    fastComments\n    commentColors\n    moreRecommendList {\n      user {\n        id\n        avatar\n        name\n        __typename\n      }\n      watchingCount\n      poster\n      coverUrl\n      caption\n      id\n      playUrls {\n        quality\n        url\n        __typename\n      }\n      quality\n      gameInfo {\n        category\n        name\n        pubgSurvival\n        type\n        kingHero\n        __typename\n      }\n      hasRedPack\n      liveGuess\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"
                };
                WebSockToken = PostMoths(LiveDetail, zbj);
                JObject paramJson = JsonConvert.DeserializeObject(WebSockToken) as JObject;
                liveStreamId = WebSockToken = paramJson["data"]["webLiveDetail"]["liveStream"]["liveStreamId"].ToString();
                object WebSocketInfoQuery = new
                {
                    operationName = "WebSocketInfoQuery",
                    variables = new { liveStreamId = WebSockToken },
                    query = "query WebSocketInfoQuery($liveStreamId: String) {\n  webSocketInfo(liveStreamId: $liveStreamId) {\n    token\n    webSocketUrls\n    __typename\n  }\n}\n"
                };
                WebSockToken = PostMoths(WebSocketInfoQuery, zbj);
                WebSockToken = WebSockToken.TrimEnd('}') + ",\"liveStreamId\":\"" + liveStreamId + "\",\"sjs\":\"" + randomNum(16) + "_" + LJSheng.Common.LCommon.GetTimeStamp(DateTime.Now) + "\"}}}";
            }
            catch (Exception err) { WebSockToken = "QQ9021616"; }

            return WebSockToken;
        }

        public static string randomNum(int length)
        {
            Random rdm = new Random();
            string text = string.Empty;
            string charset = "bjectSymhasOwnProp-0123456789ABCDEFGHIJKLMNQRTUVWXYZ_dfgiklquvxz";

            for (int i = 0; i < length; i++)
            {
                text += charset[(int)Math.Ceiling(35 * rdm.NextDouble())];
            }
            return text;
        }

        /// <summary>
        /// 压缩HTTP数据包
        /// </summary>
        /// <param name="stm"></param>
        /// <returns></returns>
        public static string DecompressGzip(Stream stm)
        {
            string strHTML = "";

            GZipStream gzip = new GZipStream(stm, CompressionMode.Decompress);//解压缩
            using (StreamReader reader = new StreamReader(gzip, Encoding.GetEncoding("UTF-8")))//中文编码处理
            {
                strHTML = reader.ReadToEnd();
            }

            return strHTML;
        }

        public static string PostMoths(object obj_model, string zbj)
        {
            string url = "https://live.kuaishou.com";
            string param = JsonConvert.SerializeObject(obj_model);
            System.Net.HttpWebRequest request;
            request = (System.Net.HttpWebRequest)WebRequest.Create(url + "/m_graphql");
            request.Method = "POST";
            request.Host = "live.kuaishou.com";
            request.Accept = @"*/*";
            request.KeepAlive = true;
            request.ContentType = "application/json";
            request.Referer = url + "/u/" + zbj;
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36";

            request.Headers.Add("Origin", url);
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
            request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
            //request.Headers.Add("DNT", "1");
            request.Headers.Add("Sec-Fetch-Dest", "empty");
            request.Headers.Add("Sec-Fetch-Mode", "cors");
            request.Headers.Add("Sec-Fetch-Site", "same-origin");
            //request.Headers.Add("needLoginToWatchHD", "1");
            //request.Headers.Add("Cookie","kuaishou.live.bfb1s=477cb0011daca84b36b3a4676857e5a1; clientid=3; did=web_abfb3ee1812f4e53950c14169b49d5ca; client_key=65890b29; didv=1576160674000;");

            byte[] payload;
            payload = System.Text.Encoding.UTF8.GetBytes(param);
            request.ContentLength = payload.Length;
            string strValue = "";
            try
            {
                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();
                System.Net.HttpWebResponse response;
                response = (HttpWebResponse)request.GetResponse();
                if (response.ContentEncoding.ToLower().Contains("gzip"))
                {
                    strValue = DecompressGzip(response.GetResponseStream());
                }
                else
                {
                    string encoding = response.ContentEncoding;
                    if (encoding == null || encoding.Length < 1)
                    {
                        encoding = "UTF-8"; //默认编码  
                    }
                    StreamReader Reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                    string StrDate = "";
                    while ((StrDate = Reader.ReadLine()) != null)
                    {
                        strValue += StrDate;
                    }
                }
            }
            catch (Exception e)
            {
                strValue = e.Message;
            }
            return strValue;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}